import { Injectable } from '@angular/core';
import {ConfigService} from "./config.service";
import {HttpClient} from "@angular/common/http";
import { Storage } from '@ionic/storage';
@Injectable({
  providedIn: 'root'
})
export class AuthService {
  constructor(private http:HttpClient
    ,private config:ConfigService
    ,private storage:Storage) { }


  private refreshTokenUrl=this.config.HOST+"/auth/refreshToken";
  refreshToken(){
    let last:number= 0;
    let current:number=new Date().getTime();
    this.storage.get("FRESHTIME")
      .then((value:number)=>{
        console.log("currenttime"+current);
        console.log("lastfreshtime"+value);
        if(current-value>(10*60*1000)){
          this.http.get(this.refreshTokenUrl).toPromise()
            .then((data:any)=>{
              if(data.token!='error'){
                this.storage.set("TOKEN",data.token);

                this.storage.set("FRESHTIME",current);

                console.log("令牌成功刷新");
              }
            })



        }



      })


  }


  private loginUrl=this.config.HOST+"/public/login";

  loginbyUserNameAndPass(username:string,
                         password:string){
    let parm={
      "username":username,
      "password":password
    }

    return this.http.post(this.loginUrl,parm).toPromise();


  }





}
